// 选择ztree
var setting = {
  check: {
    enable: true
  },
  data: {
    simpleData: {
      enable: false
    }
  },
  view: {
    showIcon: false
	},
	callback: {
		onCheck: zTreeOnCheck
	}
};

/**标准数据格式*/
var zNodes = [];

// 选中的zTree值
var participantId = [];

var modelType;
var modelId;

var typeOneUserList; // type1可见人员集合--补卡
var typeTwoUserList; // type2可见人员集合--请假
var typeThreeUserList; // type3可见人员集合--外出

$(function() {
  getApprovalTypeList(); // 获取审批类型列表
  getTeamUserArr(); // 获取部门与人员集合

  // 切换可见范围
  $("#selectVisualRange").on("change", function() {
    var val = $(this).val();
    if (val == 2) { // 部分可见显示人员选择框
      $(".zTreeDemoBackground").css({ visibility: 'visible' });
    } else {
      $(".zTreeDemoBackground").css({ visibility: 'hidden' });
    }
  });

  // 保存选择人员
  $("#sayerBox-btn").on("click", function() {
    console.log("modelType="+modelType);
    console.log("modelId="+modelId);
    getzTreeChecked(modelType, modelId);
    layer.closeAll('page')
  })

});

//编辑
function brandEdit(attendanceId) {
  ly.goto("attendanceManagement-creat.html?id=" + attendanceId + "&attendanceType=2")
}

//删除
function deleteBrand(attendanceId) {
  var url = site.apiUrl + "/back/attendanceBack/deleteAttendanceSettingsById";
  ly.confirm("是否删除？", function() {
    request({
      url: url,
      data: { "ids": attendanceId },
      type: "get",
      ajaxform: 'true',
      callback: function(f) {
        if (f.code == "rest.success") {
          ly.toast("删除成功");
          $("#attendanceManagementList").getList.refresh(); //刷新当前分页
        }
      }
    });
  });
}

// 获取审批类型列表
function getApprovalTypeList() {
  request({
    url: site.apiUrl + '/back/approvalSettings/selectApprovalVisualRangeSettingByAll',
    type: "post",
    ajaxform: 'true',
    callback: function(f) {
      if (f.code == "rest.success") {
        var $approvalmanagelistEle = $("#approval-manage-list");
        $approvalmanagelistEle.html('');
        $.each(f.result, function(i, o) {
          if (o.approvalType == 1) { // 补卡
            typeOneUserList = o.visibleUsers;
          } else if (o.approvalType == 2) { // 请假
            typeTwoUserList = o.visibleUsers;
          } else if (o.approvalType == 3) { // 外出
            typeThreeUserList = o.visibleUsers;
          }
          var itemHTML = '';
          itemHTML += '<div class="list_one">';
          itemHTML += '<div class="item_name">'+ o.approvalTypeDisplay +'</div>';
          itemHTML += '<div class="visible_range">';
          itemHTML += '<div class="visible_title">可见范围</div>';
          itemHTML += '<div class="handle">';
          itemHTML += '<span>'+ o.isVisibleDisplay +'</span>';
          console.log("approvalVisualRangeId="+ o.approvalVisualRangeId);
          itemHTML += '<button onclick=\'setVisibleRange('+ o.approvalType +', "'+ o.approvalVisualRangeId +'", "'+ o.isVisibleDisplay +'")\'>修改</button>';
          itemHTML += '</div>';
          itemHTML += '</div>';
          itemHTML += '<div class="handle_option">';
          itemHTML += '<div class="handle_button edit_button" onclick="goApprovalGroupPage('+ o.approvalType +')">编辑</div>';
          // itemHTML += '<div class="handle_button ss_button" onclick="setIsUsing('+ o.isUsing +', '+ o.approvalType +')">'+ o.isUsingDisplay +'</div>';
          if(o.isUsing==1){
            itemHTML += '<div class="handle_button ss_button" onclick="setIsUsing('+ o.isUsing +', '+ o.approvalType +',event)"><label><input class="mui-switch mui-switch-anim" type="checkbox" checked="checked"></label></div>';
          }else{
            itemHTML += '<div class="handle_button ss_button" onclick="setIsUsing('+ o.isUsing +', '+ o.approvalType +',event)"><label><input class="mui-switch mui-switch-anim" type="checkbox"></label></div>';
          }
          itemHTML += '</div>';
          itemHTML += '</div>';
          itemHTML += '</div>';
          $approvalmanagelistEle.append(itemHTML);

        })
      }
    }
  });
}

// 修改可见范围
function setVisibleRange(type, id, visibleDisplay) {
  console.log("type="+type);
  console.log('id='+ id);
  console.log('visibleDisplay='+ visibleDisplay);

  modelType = type;
  modelId = id;
  layer.open({
    title: false,
    type: 1,
    area: ['600px'], //设置宽度,高度自适应
    closeBtn: 0,
    content: $(".layerBox"),
    success: function(layero, index) {
      if (visibleDisplay == '全部可见') {
        $("#selectVisualRange").val('1');
        $(".zTreeDemoBackground").css({ visibility: 'hidden' });
        // 初始化zTree
        $("#ztreeCheckedNames").html('');
        var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
        zTreeObj.checkAllNodes(false); // 清除所有节点选中状态
        zTreeObj.expandAll(false); // 收起所有节点
      } else {
        showCheckedUser(type);
        $("#selectVisualRange").val('2');
        $(".zTreeDemoBackground").css({ visibility: 'visible' });
      }
      $("#layui-layer" + index).find(".goback,.icon-close").on("click", function() {
        layer.close(index);
      });
    }
  });
}

// 跳转审批分组页
function goApprovalGroupPage(type) {
  ly.goto("approval-group-list.html?approvalType=" + type);
}

// 设置启用/停用
function setIsUsing(currentStatus, type,event) {
  console.log(event)
  var that = event&&event.target;
  var tipsText = ''; // 提示语
  var setVal;
  if (currentStatus == 0) { // 停用
    tipsText = '确定启用吗？';
    setVal = 1;
  } else if (currentStatus == 1) { // 启用
    tipsText = '确定停用吗？'
    setVal = 0;
  }
  ly.confirm(tipsText, function() {
    request({
      url: site.apiUrl + '/back/approvalSettings/usingOrDisableApprovalType',
      data: {
        onOff: setVal,
        approvalType: type,
      },
      type: "post",
      ajaxform: 'true',
      callback: function(f) {
        if (f.code == "rest.success") {
          ly.toast("设置成功");
          getApprovalTypeList(); // 获取审批类型列表
        }else{
          if(currentStatus == 0){
            $(that).removeAttr('checked');
          }else{
            $(that).prop('checked',true); 
          }
        }
      }
    });
  },function(){
    if(currentStatus == 0){
      $(that).removeAttr('checked');
    }else{
      $(that).prop('checked',true); 
    }
  });
}

// 获取部门与人员集合
function getTeamUserArr() {
  request({
    url: site.apiUrl + "/back/team/selectTeamUserByGroupsBack",
    type: "get",
    callback: function(f) {
      if (f.code == "rest.success") {
				zNodes = f.result;
        $("#ztreeCheckedNames").html('');
        $.fn.zTree.init($("#treeDemo"), setting, zNodes); // 加载ztree
        var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
        zTreeObj.checkAllNodes(false); // 清除所有节点选中状态
        zTreeObj.expandAll(false); // 收起所有节点
      }
    }
  });
}

// 部分可见状态时zTree展示可见人员
function showCheckedUser(type) {
  var userList;
  if (type == 1) { // 补卡
    userList = typeOneUserList;
  } else if (type == 2) { // 请假
    userList = typeTwoUserList;
  } else if (type == 3) { // 外出
    userList = typeThreeUserList;
  }
  if (userList && userList.length > 0) {
    var viewCheckedPerson = zNodes.map(function (item) {
      if (item.children && item.children.length > 0) {
        var childrenCheckOption = item.children;
        var newChildren = childrenCheckOption.map(function (itm) {
          // 判断选中项，true设置cheked=true，反之设为false
          var isCheckedOption = userList.some(function (items) {
            return items.userId === itm.userId;
          });
          if (isCheckedOption) {
            itm.checked = true; // 为true时zTree勾选当前项
          } else {
            itm.checked = false;
          }
          return itm;
        });
        item.children = newChildren;
        return item;
      } else {
        return item;
      }
    });
    $.fn.zTree.init($("#treeDemo"), setting, viewCheckedPerson); // 加载ztree
    var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
    zTreeObj.expandAll(false); // 收起所有节点
    zTreeOnCheck(); // 展示右侧选中项
  } else {
    // 初始化zTree
    $("#ztreeCheckedNames").html('');
    var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
    zTreeObj.checkAllNodes(false); // 清除所有节点选中状态
    zTreeObj.expandAll(false); // 收起所有节点
  }
}

// 获取部门与人员集合
function getTeamUser(viewData) {
	request({
    url: site.apiUrl + "/back/team/selectTeamUserByGroupsBack",
    type: "get",
    callback: function(f) {
      if (f.code == "rest.success") {
				zNodes = f.result;
				if (!viewData) { // 新增
					$("#ztreeCheckedNames").html('');
					$.fn.zTree.init($("#treeDemo"), setting, zNodes); // 加载ztree
					var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
					zTreeObj.checkAllNodes(false); // 清除所有节点选中状态
					zTreeObj.expandAll(false); // 收起所有节点
				} else { // 编辑
					var viewCheckedPerson = zNodes.map(function (item) {
						if (item.children && item.children.length > 0) {
							var childrenCheckOption = item.children;
							var newChildren = childrenCheckOption.map(function (itm) {
								// 判断选中项，true设置cheked=true，反之设为false
								var isCheckedOption = viewData.visibleUsers.some(function (items) {
									return items.userId === itm.userId;
								});
								if (isCheckedOption) {
									itm.checked = true; // 为true时zTree勾选当前项
								} else {
									itm.checked = false;
								}
								return itm;
							});
							item.children = newChildren;
							return item;
						} else {
              return item;
            }
					});
					$.fn.zTree.init($("#treeDemo"), setting, viewCheckedPerson); // 加载ztree
					var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
					zTreeObj.expandAll(false); // 收起所有节点
					zTreeOnCheck(); // 展示右侧选中项
				}
      }
    }
  });
}

// zTree发生改变
function zTreeOnCheck(event, treeId, treeNode) {
	var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
  var checkedNodes = zTreeObj.getCheckedNodes();
	$("#ztreeCheckedNames").html('');
	for(var i = 0; i < checkedNodes.length; i++) {
    if (!checkedNodes[i].children) {
      $("#ztreeCheckedNames").append('<li>'+ checkedNodes[i].name +'</li>')
    }
	}
};

// 修改可见范围
function getzTreeChecked(type, id) {
  var visualRange = $("#selectVisualRange option:selected").val();
	participantId = [];
  var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
	var checkedNodes = zTreeObj.getCheckedNodes();
	$.each(checkedNodes, function(i, o) {
		if (checkedNodes[i].userId) {
			participantId.push(checkedNodes[i].userId);
		}
  })
  
  request({
    url: site.apiUrl + '/back/approvalSettings/insertOrUpdateApprovalVisualRangeSetting',
    data: {
      approvalType: type,
      approvalVisualRangeId: id,
      visualRange: visualRange,
      everyMenIds: participantId.toString(),
    },
    type: "post",
    callback: function(f) {
      if (f.code == "rest.success") {
        ly.toast(f.desc);
        getApprovalTypeList(); // 获取审批类型列表
      } else {
        ly.toast(f.desc);
      }
    }
  });

}
